import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CreateExamFrame extends JFrame {
    private User teacher;
    private TeacherMainFrame parent;
    private Exam exam; // 编辑时使用
    private boolean isEdit = false;

    // 基本信息组件
    private JTextField titleField;
    private JTextArea descriptionArea;
    private JSpinner startDateSpinner;
    private JSpinner endDateSpinner;
    private JSpinner durationSpinner;
    private JTextField totalScoreField;
    private JTextField passScoreField;
    private JComboBox<String> statusComboBox;
    private JCheckBox autoGradeCheckBox;

    // 题目管理组件
    private JTable questionTable;
    private DefaultTableModel questionTableModel;
    private JButton addQuestionButton;
    private JButton editQuestionButton;
    private JButton deleteQuestionButton;
    private List<Question> questions = new ArrayList<>();

    // 操作按钮
    private JButton saveButton;
    private JButton cancelButton;

    // DAO
    private ExamDAO examDAO;
    private QuestionDAO questionDAO;

    public CreateExamFrame(User teacher, TeacherMainFrame parent) {
        this.teacher = teacher;
        this.parent = parent;
        this.isEdit = false;
        this.examDAO = new ExamDAO();
        this.questionDAO = new QuestionDAO();

        initComponents();
        setupLayout();
        setupEvents();
    }

    public CreateExamFrame(User teacher, TeacherMainFrame parent, Exam exam) {
        this.teacher = teacher;
        this.parent = parent;
        this.exam = exam;
        this.isEdit = true;
        this.examDAO = new ExamDAO();
        this.questionDAO = new QuestionDAO();

        initComponents();
        setupLayout();
        setupEvents();
        loadExamData();
    }

    private void initComponents() {
        setTitle(isEdit ? "编辑考试" : "创建考试");
        setSize(1400, 1000); // 进一步增大窗口
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setResizable(true);

        // 字体设置
        Font labelFont = new Font("微软雅黑", Font.BOLD, 18);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);

        // 考试名称输入框
        titleField = new JTextField();
        titleField.setFont(fieldFont);
        titleField.setPreferredSize(new Dimension(500, 45));

        // 考试描述区域 - 显著增大
        descriptionArea = new JTextArea(8, 50);
        descriptionArea.setFont(fieldFont);
        descriptionArea.setLineWrap(true);
        descriptionArea.setWrapStyleWord(true);
        descriptionArea.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.GRAY),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)));

        // 时间选择器
        startDateSpinner = new JSpinner(new SpinnerDateModel());
        endDateSpinner = new JSpinner(new SpinnerDateModel());
        JSpinner.DateEditor startEditor = new JSpinner.DateEditor(startDateSpinner, "yyyy-MM-dd HH:mm");
        JSpinner.DateEditor endEditor = new JSpinner.DateEditor(endDateSpinner, "yyyy-MM-dd HH:mm");
        startDateSpinner.setEditor(startEditor);
        endDateSpinner.setEditor(endEditor);
        startDateSpinner.setFont(fieldFont);
        endDateSpinner.setFont(fieldFont);
        startDateSpinner.setPreferredSize(new Dimension(220, 45));
        endDateSpinner.setPreferredSize(new Dimension(220, 45));

        // 时长输入框
        durationSpinner = new JSpinner(new SpinnerNumberModel(120, 1, 999, 1));
        durationSpinner.setFont(fieldFont);
        durationSpinner.setPreferredSize(new Dimension(150, 45));

        // 总分输入框 - 显著增大
        totalScoreField = new JTextField("100");
        totalScoreField.setFont(new Font("微软雅黑", Font.BOLD, 18));
        totalScoreField.setPreferredSize(new Dimension(150, 45));
        totalScoreField.setHorizontalAlignment(JTextField.CENTER);
        totalScoreField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)));

        // 及格分输入框 - 显著增大
        passScoreField = new JTextField("60");
        passScoreField.setFont(new Font("微软雅黑", Font.BOLD, 18));
        passScoreField.setPreferredSize(new Dimension(150, 45));
        passScoreField.setHorizontalAlignment(JTextField.CENTER);
        passScoreField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)));

        // 状态下拉框
        statusComboBox = new JComboBox<>(new String[] { "draft", "published" });
        statusComboBox.setFont(fieldFont);
        statusComboBox.setPreferredSize(new Dimension(150, 45));
        statusComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
                    boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value.equals("draft")) {
                    setText("草稿");
                } else if (value.equals("published")) {
                    setText("已发布");
                }
                return this;
            }
        });

        autoGradeCheckBox = new JCheckBox("自动阅卷", true);
        autoGradeCheckBox.setFont(fieldFont);

        // 题目表格
        String[] columnNames = { "序号", "题型", "题目内容", "分值", "操作" };
        questionTableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        questionTable = new JTable(questionTableModel);
        questionTable.setRowHeight(45);
        questionTable.setFont(fieldFont);
        questionTable.getTableHeader().setFont(labelFont);
        questionTable.getTableHeader().setPreferredSize(new Dimension(0, 45));
        questionTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 设置表格列宽
        questionTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        questionTable.getColumnModel().getColumn(1).setPreferredWidth(120);
        questionTable.getColumnModel().getColumn(2).setPreferredWidth(600);
        questionTable.getColumnModel().getColumn(3).setPreferredWidth(100);
        questionTable.getColumnModel().getColumn(4).setPreferredWidth(120);

        // 题目管理按钮
        Dimension buttonSize = new Dimension(140, 50);

        addQuestionButton = new JButton("添加题目");
        addQuestionButton.setFont(labelFont);
        addQuestionButton.setPreferredSize(buttonSize);
        addQuestionButton.setBackground(new Color(40, 167, 69));
        addQuestionButton.setForeground(Color.WHITE);

        editQuestionButton = new JButton("编辑题目");
        editQuestionButton.setFont(labelFont);
        editQuestionButton.setPreferredSize(buttonSize);
        editQuestionButton.setBackground(new Color(255, 193, 7));
        editQuestionButton.setForeground(Color.BLACK);

        deleteQuestionButton = new JButton("删除题目");
        deleteQuestionButton.setFont(labelFont);
        deleteQuestionButton.setPreferredSize(buttonSize);
        deleteQuestionButton.setBackground(new Color(220, 53, 69));
        deleteQuestionButton.setForeground(Color.WHITE);

        // 操作按钮
        saveButton = new JButton(isEdit ? "保存修改" : "创建考试");
        saveButton.setFont(new Font("微软雅黑", Font.BOLD, 18));
        saveButton.setPreferredSize(new Dimension(160, 55));
        saveButton.setBackground(new Color(40, 167, 69));
        saveButton.setForeground(Color.WHITE);

        cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 18));
        cancelButton.setPreferredSize(new Dimension(120, 55));
        cancelButton.setBackground(new Color(108, 117, 125));
        cancelButton.setForeground(Color.WHITE);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));

        // 顶部标题
        JPanel titlePanel = new JPanel();
        titlePanel.setBackground(new Color(70, 130, 180));
        titlePanel.setPreferredSize(new Dimension(1400, 80));
        JLabel titleLabel = new JLabel(isEdit ? "编辑考试" : "创建考试", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(Color.WHITE);
        titlePanel.add(titleLabel);

        // 主要内容面板
        JPanel mainPanel = new JPanel(new BorderLayout(15, 15));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 基本信息面板
        JPanel basicInfoPanel = createBasicInfoPanel();

        // 题目管理面板
        JPanel questionPanel = createQuestionPanel();

        // 底部按钮面板
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        bottomPanel.add(saveButton);
        bottomPanel.add(cancelButton);

        mainPanel.add(basicInfoPanel, BorderLayout.NORTH);
        mainPanel.add(questionPanel, BorderLayout.CENTER);

        add(titlePanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    private JPanel createBasicInfoPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 5));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "基本信息",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(70, 130, 180)));

        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);

        // 上半部分：考试名称和描述
        JPanel topPanel = new JPanel(new BorderLayout(10, 5));

        // 考试名称行
        JPanel namePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel nameLabel = new JLabel("考试名称:");
        nameLabel.setFont(labelFont);
        nameLabel.setPreferredSize(new Dimension(80, 35));
        titleField.setPreferredSize(new Dimension(400, 35));
        namePanel.add(nameLabel);
        namePanel.add(titleField);
        topPanel.add(namePanel, BorderLayout.NORTH);

        // 考试描述（缩小高度）
        JPanel descPanel = new JPanel(new BorderLayout(5, 5));
        JLabel descLabel = new JLabel("考试描述:");
        descLabel.setFont(labelFont);
        descPanel.add(descLabel, BorderLayout.NORTH);

        // 调整描述区域的显示设置
        descriptionArea.setRows(3); // 从8行减少到3行
        descriptionArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        JScrollPane descScrollPane = new JScrollPane(descriptionArea);
        descScrollPane.setPreferredSize(new Dimension(1200, 80)); // 从180减少到80
        descScrollPane.setBorder(BorderFactory.createLineBorder(new Color(70, 130, 180), 1));
        descPanel.add(descScrollPane, BorderLayout.CENTER);
        topPanel.add(descPanel, BorderLayout.CENTER);

        // 下半部分：时间、分数等设置（合并到一行）
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 5));

        // 时间设置
        JLabel startLabel = new JLabel("开始:");
        startLabel.setFont(labelFont);
        startDateSpinner.setPreferredSize(new Dimension(180, 35));
        bottomPanel.add(startLabel);
        bottomPanel.add(startDateSpinner);

        JLabel endLabel = new JLabel("结束:");
        endLabel.setFont(labelFont);
        endDateSpinner.setPreferredSize(new Dimension(180, 35));
        bottomPanel.add(endLabel);
        bottomPanel.add(endDateSpinner);

        JLabel durationLabel = new JLabel("时长:");
        durationLabel.setFont(labelFont);
        durationSpinner.setPreferredSize(new Dimension(80, 35));
        bottomPanel.add(durationLabel);
        bottomPanel.add(durationSpinner);

        // 分数设置
        JLabel scoreLabel = new JLabel("总分:");
        scoreLabel.setFont(labelFont);
        scoreLabel.setForeground(new Color(70, 130, 180));
        totalScoreField.setPreferredSize(new Dimension(80, 35));
        bottomPanel.add(scoreLabel);
        bottomPanel.add(totalScoreField);

        JLabel passLabel = new JLabel("及格分:");
        passLabel.setFont(labelFont);
        passLabel.setForeground(new Color(70, 130, 180));
        passScoreField.setPreferredSize(new Dimension(80, 35));
        bottomPanel.add(passLabel);
        bottomPanel.add(passScoreField);

        // 状态和自动阅卷
        JLabel statusLabel = new JLabel("状态:");
        statusLabel.setFont(labelFont);
        statusComboBox.setPreferredSize(new Dimension(100, 35));
        bottomPanel.add(statusLabel);
        bottomPanel.add(statusComboBox);

        autoGradeCheckBox.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        bottomPanel.add(autoGradeCheckBox);

        panel.add(topPanel, BorderLayout.CENTER);
        panel.add(bottomPanel, BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createQuestionPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "题目管理",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 20),
                new Color(70, 130, 180)));

        // 题目表格 - 移除固定高度，让它自适应
        JScrollPane scrollPane = new JScrollPane(questionTable);
        scrollPane.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        // 设置最小高度，确保有足够的显示空间
        scrollPane.setMinimumSize(new Dimension(1300, 500));

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 10));
        buttonPanel.add(addQuestionButton);
        buttonPanel.add(editQuestionButton);
        buttonPanel.add(deleteQuestionButton);

        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    private void setupEvents() {
        saveButton.addActionListener(e -> saveExam());
        cancelButton.addActionListener(e -> dispose());

        addQuestionButton.addActionListener(e -> addQuestion());
        editQuestionButton.addActionListener(e -> editQuestion());
        deleteQuestionButton.addActionListener(e -> deleteQuestion());

        // 双击编辑题目
        questionTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    editQuestion();
                }
            }
        });
    }

    private void loadExamData() {
        if (exam == null)
            return;

        titleField.setText(exam.getTitle());
        descriptionArea.setText(exam.getDescription());
        startDateSpinner.setValue(exam.getStartTime());
        endDateSpinner.setValue(exam.getEndTime());
        durationSpinner.setValue(exam.getDuration());
        totalScoreField.setText(String.valueOf(exam.getTotalScore()));
        passScoreField.setText(String.valueOf(exam.getPassScore()));
        statusComboBox.setSelectedItem(exam.getStatus());
        autoGradeCheckBox.setSelected(exam.isAutoGrade());

        // 加载题目
        questions = questionDAO.getQuestionsByExamId(exam.getId());
        refreshQuestionTable();
    }

    private void addQuestion() {
        QuestionEditDialog dialog = new QuestionEditDialog(this, null, questions.size() + 1);
        dialog.setVisible(true);

        Question newQuestion = dialog.getQuestion();
        if (newQuestion != null) {
            questions.add(newQuestion);
            refreshQuestionTable();
            updateTotalScore();
        }
    }

    private void editQuestion() {
        int selectedRow = questionTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要编辑的题目！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        Question question = questions.get(selectedRow);
        QuestionEditDialog dialog = new QuestionEditDialog(this, question, selectedRow + 1);
        dialog.setVisible(true);

        Question editedQuestion = dialog.getQuestion();
        if (editedQuestion != null) {
            questions.set(selectedRow, editedQuestion);
            refreshQuestionTable();
            updateTotalScore();
        }
    }

    private void deleteQuestion() {
        int selectedRow = questionTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的题目！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int result = JOptionPane.showConfirmDialog(this, "确定要删除这个题目吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            questions.remove(selectedRow);
            // 重新设置题目顺序
            for (int i = 0; i < questions.size(); i++) {
                questions.get(i).setQuestionOrder(i + 1);
            }
            refreshQuestionTable();
            updateTotalScore();
        }
    }

    private void refreshQuestionTable() {
        questionTableModel.setRowCount(0);
        for (int i = 0; i < questions.size(); i++) {
            Question q = questions.get(i);
            String questionText = q.getQuestionText();
            if (questionText.length() > 50) {
                questionText = questionText.substring(0, 50) + "...";
            }

            Object[] row = {
                    i + 1,
                    getQuestionTypeText(q.getQuestionType()),
                    questionText,
                    q.getScore(),
                    "编辑"
            };
            questionTableModel.addRow(row);
        }
    }

    private void updateTotalScore() {
        double total = questions.stream().mapToDouble(Question::getScore).sum();
        totalScoreField.setText(String.valueOf(total));
    }

    private void saveExam() {
        // 验证输入
        if (!validateInput()) {
            return;
        }

        try {
            // 创建或更新考试对象
            Exam examToSave = isEdit ? exam : new Exam();

            examToSave.setTitle(titleField.getText().trim());
            examToSave.setDescription(descriptionArea.getText().trim());
            examToSave.setTeacherId(teacher.getId());
            examToSave.setStartTime(new Timestamp(((Date) startDateSpinner.getValue()).getTime()));
            examToSave.setEndTime(new Timestamp(((Date) endDateSpinner.getValue()).getTime()));
            examToSave.setDuration((Integer) durationSpinner.getValue());
            examToSave.setTotalScore(Double.parseDouble(totalScoreField.getText()));
            examToSave.setPassScore(Double.parseDouble(passScoreField.getText()));
            examToSave.setStatus((String) statusComboBox.getSelectedItem());
            examToSave.setAutoGrade(autoGradeCheckBox.isSelected());

            boolean success;
            if (isEdit) {
                success = examDAO.updateExam(examToSave);
                if (success) {
                    // 删除原有题目，重新保存
                    questionDAO.deleteQuestionsByExamId(examToSave.getId());
                }
            } else {
                success = examDAO.createExam(examToSave);
            }

            if (success) {
                // 保存题目
                for (Question question : questions) {
                    question.setExamId(examToSave.getId());
                    questionDAO.createQuestion(question);
                }

                JOptionPane.showMessageDialog(this,
                        isEdit ? "考试修改成功！" : "考试创建成功！",
                        "成功",
                        JOptionPane.INFORMATION_MESSAGE);

                parent.refreshExamList();
                dispose();
            } else {
                JOptionPane.showMessageDialog(this,
                        isEdit ? "考试修改失败！" : "考试创建失败！",
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "保存失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private boolean validateInput() {
        if (titleField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入考试名称！", "验证失败", JOptionPane.WARNING_MESSAGE);
            return false;
        }

        Date startDate = (Date) startDateSpinner.getValue();
        Date endDate = (Date) endDateSpinner.getValue();

        if (startDate.after(endDate)) {
            JOptionPane.showMessageDialog(this, "开始时间不能晚于结束时间！", "验证失败", JOptionPane.WARNING_MESSAGE);
            return false;
        }

        try {
            double totalScore = Double.parseDouble(totalScoreField.getText());
            double passScore = Double.parseDouble(passScoreField.getText());

            if (totalScore <= 0 || passScore < 0 || passScore > totalScore) {
                JOptionPane.showMessageDialog(this, "分数设置不正确！", "验证失败", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "分数必须是数字！", "验证失败", JOptionPane.WARNING_MESSAGE);
            return false;
        }

        if (questions.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请至少添加一个题目！", "验证失败", JOptionPane.WARNING_MESSAGE);
            return false;
        }

        return true;
    }

    private String getQuestionTypeText(String type) {
        switch (type) {
            case "single_choice":
                return "单选题";
            case "multiple_choice":
                return "多选题";
            case "true_false":
                return "判断题";
            case "fill_blank":
                return "填空题";
            case "essay":
                return "问答题";
            default:
                return type;
        }
    }
}